package com.sit.estatemanagementserver.service;

import com.sit.estatemanagementserver.dao.FacilityDao;
import com.sit.estatemanagementserver.dao.FacilityRentalDao;
import com.sit.estatemanagementserver.enity.Facility;
import com.sit.estatemanagementserver.enity.FacilityRental;
import com.sit.estatemanagementserver.enity.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class FacilityService {
    @Autowired
    private FacilityDao facilityDao;

    @Autowired
    private FacilityRentalDao facilityRentalDao;

    //查询
    public List<Facility> getAllFacilities() {
        // 无需修改
        return facilityDao.getAllFacilities();
    }

    // 添加设施
    public boolean addFacility(Facility facility) {
        // 无需修改
        return facilityDao.addFacility(facility);
    }

    // 通过ID查看设施
    public Facility getFacilityById(String facilityId) {
        // 无需修改
        return facilityDao.getFacility(facilityId);
    }

    // 修改设施
    public boolean updateFacility(Facility facility) {
        // 无需修改
        return facilityDao.updateFacility(facility);
    }
    // 删除设施
    public boolean deleteFacility(String facilityId) {
        // 无需修改
        return facilityDao.deleteFacility(facilityId);
    }

    /**
     * 重构: 预定设施，增加时间冲突检测
     * @param facilityRental 包含预定信息的实体
     * @return 返回一个包含成功或失败信息的Response对象
     */
    public Response<Object> addFacilityRental(FacilityRental facilityRental) {
        // 1. 调用DAO进行时间冲突检测
        List<FacilityRental> overlappingRentals = facilityRentalDao.findOverlappingRentals(
                facilityRental.getFacilityId(),
                facilityRental.getStartTime(),
                facilityRental.getEndTime()
        );

        // 2. 如果列表不为空，说明存在时间冲突
        if (!overlappingRentals.isEmpty()) {
            return Response.error("预定失败：该时间段已被占用。");
        }

        // 3. 没有冲突，执行添加操作
        boolean success = facilityRentalDao.addFacilityRental(facilityRental);
        if (success) {
            return Response.success();
        } else {
            return Response.error("预定失败：数据库操作异常。");
        }
    }
}